<!--
 * @Descripttion: 保养记录表单
 * @LastEditors: xzh
 * @LastEditTime: 2023-11-04 22:24:15
-->
<template>
  <DileDrawer
    v-model="upkeepRecordForm.visible"
    :loading="upkeepRecordForm.loading"
    size="80%"
    @sure="hanldeSure"
  >
    <template #header>
      <span>{{
        $t(`table.btnArr.${!upkeepRecordForm.formData.id ? "add" : "edit"}`)
      }}</span>
    </template>
    <template #default>
      <el-form
        ref="formRef"
        class="el-form-card"
        :model="upkeepRecordForm.formData"
        :rules="formRules"
        label-width="8rem"
        size="large"
        status-icon
      >
        <!-- 模具信息 -->
        <el-card>
          <template #header>
            <span>{{ $t("page.moldManageArr.moldArchivesArr.moldInfo") }}</span>
          </template>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.moldManageArr.moldArchivesArr.name')"
              prop="relMold.name"
            >
              <el-input
                v-model="upkeepRecordForm.formData.relMold.name"
                readonly
                :placeholder="$t('common.select')"
                @click="() => dileSelectItemTableRef.init()"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.moldManageArr.moldArchivesArr.code')"
            >
              <el-input
                v-model="upkeepRecordForm.formData.relMold.code"
                disabled
                :placeholder="$t('common.systemAutoBringOut')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.moldManageArr.moldArchivesArr.specification')"
            >
              <el-input
                v-model="upkeepRecordForm.formData.relMold.specification"
                disabled
                :placeholder="$t('common.systemAutoBringOut')"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="$t('page.moldManageArr.moldType')">
              <el-input
                v-model="upkeepRecordForm.formData.relMold.extJson.typeName"
                disabled
                :placeholder="$t('common.systemAutoBringOut')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('page.systemManageArr.position')">
              <el-input
                v-model="upkeepRecordForm.formData.relMold.extJson.positionName"
                disabled
                :placeholder="$t('common.systemAutoBringOut')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.moldManageArr.moldArchivesArr.factory')"
            >
              <el-input
                v-model="upkeepRecordForm.formData.relMold.extJson.factoryName"
                disabled
                :placeholder="$t('common.systemAutoBringOut')"
              />
            </el-form-item>
          </el-col>
        </el-card>
        <!-- 保养任务信息 -->
        <el-card>
          <template #header>
            <span>{{
              $t("page.equipUpkeepArr.upkeepRecordArr.recordInfo")
            }}</span>
          </template>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.moldUpkeepArr.upkeepRecordArr.code')"
            >
              <el-input
                v-model="upkeepRecordForm.formData.code"
                disabled
                :placeholder="$t('common.systemAutoGenerate')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.moldUpkeepArr.upkeepRecordArr.name')"
              prop="name"
            >
              <el-input
                v-model="upkeepRecordForm.formData.name"
                :placeholder="$t('common.enter')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipUpkeepArr.upkeepRecordArr.urgency')"
            >
              <el-select
                v-model="upkeepRecordForm.formData.urgencyLevel"
                :placeholder="$t('common.select')"
              >
                <el-option
                  v-for="urgency in Object.keys(upkeepRecordUrgencyEnum)"
                  :key="urgency"
                  :label="
                    $t(
                      `page.equipUpkeepArr.upkeepRecordArr.urgencyArr.${urgency}`
                    )
                  "
                  :value="urgency"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipRepairArr.repairRecordArr.isStop')"
            >
              <el-checkbox
                v-model="upkeepRecordForm.formData.isStop"
              ></el-checkbox>
            </el-form-item>
          </el-col>
        </el-card>
        <!-- 计划信息 -->
        <el-card>
          <template #header>
            <span>{{ $t("page.equipUpkeepArr.upkeepPlanArr.planInfo") }}</span>
          </template>
          <el-col :span="12">
            <el-form-item :label="$t('page.moldUpkeepArr.upkeepPlanArr.code')">
              <el-input
                v-model="upkeepRecordForm.formData.relUpkeepPlan.code"
                disabled
                :placeholder="$t('common.systemAutoBringOut')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.moldUpkeepArr.upkeepPlanArr.name')"
              prop="name"
            >
              <!-- 输入框选择对象 -->
              <DileInputSelectItem
                v-model="upkeepRecordForm.formData.maintenancePlanId"
                :selectType="selectTypeEnum.moldUpkeepPlan"
                :cacheLabel="upkeepRecordForm.formData.relUpkeepPlan.name"
                @itemSelected="handleUpkeepPlanSelected"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('page.equipUpkeepArr.upkeepPlanArr.team')">
              <el-input
                v-model="
                  upkeepRecordForm.formData.relUpkeepPlan.extJson.teamName
                "
                disabled
                :placeholder="$t('common.systemAutoBringOut')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipUpkeepArr.upkeepPlanArr.manager')"
            >
              <el-input
                v-model="
                  upkeepRecordForm.formData.relUpkeepPlan.extJson.managerName
                "
                disabled
                :placeholder="$t('common.systemAutoBringOut')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.moldUpkeepArr.upkeepPlanArr.startDate')"
            >
              <el-date-picker
                v-model="upkeepRecordForm.formData.relUpkeepPlan.startDate"
                type="datetime"
                disabled
                :placeholder="$t('common.systemAutoBringOut')"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled-date="
                (time:any) => dayjs(time).isAfter(upkeepRecordForm.formData.endDate)
                "
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.moldUpkeepArr.upkeepPlanArr.endDate')"
            >
              <el-date-picker
                v-model="upkeepRecordForm.formData.relUpkeepPlan.endDate"
                type="datetime"
                disabled
                :placeholder="$t('common.systemAutoBringOut')"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled-date="
              (time:any) => dayjs(time).isBefore(upkeepRecordForm.formData.startDate)
            "
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.moldUpkeepArr.upkeepPlanArr.executeRule')"
            >
              <!-- 输入框选择对象 -->
              <!-- <DileInputSelectItem
                v-model="upkeepRecordForm.formData.executeRuleId"
                :expand-on-click-node="false"
                :selectType="selectTypeEnum.executeRule"
                :cacheLabel="
                  upkeepRecordForm.formData.relUpkeepPlan.extJson
                    .executeRuleName
                "
                @itemSelected="handleExecuteRuleSelected"
              /> -->
              <el-input
                v-model="
                  upkeepRecordForm.formData.relUpkeepPlan.extJson
                    .executeRuleName
                "
                disabled
                :placeholder="$t('common.systemAutoBringOut')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              :label="$t('page.equipUpkeepArr.upkeepPlanArr.executeRuleRemark')"
            >
              <el-input
                v-model="
                  upkeepRecordForm.formData.relUpkeepPlan.extJson
                    .executeRuleDescription
                "
                :rows="5"
                type="textarea"
                disabled
                :placeholder="$t('common.systemAutoBringOut')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              :label="$t('page.equipUpkeepArr.upkeepPlanArr.otherPeople')"
            >
              <!-- 输入框选择对象 -->
              <DileInputSelectItem
                v-model="upkeepRecordForm.formData.relUpkeepPlan.otherUser"
                :selectType="selectTypeEnum.people"
                multiple
                :cacheLabel="
                  upkeepRecordForm.formData.relUpkeepPlan.extJson
                    .otherPeopleName
                "
              />
            </el-form-item>
          </el-col>
        </el-card>
        <!-- 保养项目 -->
        <el-card>
          <template #header>
            <span>{{ $t("page.moldUpkeepArr.upkeepItem") }}</span>
          </template>
          <!-- 关联保养项目 -->
          <RelUpkeepItem ref="relUpkeepItemRef" />
        </el-card>
        <!-- 更换备件 -->
        <el-card>
          <template #header>
            <span>{{
              $t("page.equipRepairArr.repairRecordArr.changeSpare")
            }}</span>
          </template>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.equipRepairArr.repairRecordArr.isReplace')"
            >
              <el-radio-group v-model="upkeepRecordForm.formData.isReplace">
                <el-radio :label="true">{{ $t("common.yes") }}</el-radio>
                <el-radio :label="false">{{ $t("common.no") }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-card>
        <transition name="el-fade-in">
          <!-- 模具出库表单信息 -->
          <OutBoundForm
            v-show="!!upkeepRecordForm.formData.isReplace"
            ref="outBoundFormRef"
          />
        </transition>
      </el-form>
    </template>
  </DileDrawer>
  <!-- 选择对象列表 -->
  <DileSelectItemTable
    ref="dileSelectItemTableRef"
    :selectTableType="selectTableTypeEnum.mold"
    :multiple="false"
    @sure="handleMoldSelected"
  />
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, computed, nextTick, toRef } from "vue";
import type { object_Inf } from "@/utils/typings/index.type";
import { useI18n } from "vue-i18n";
import { ElNotification, dayjs } from "element-plus";
import {
  selectTableTypeEnum,
  selectTypeEnum,
} from "@/components/dile-selectItem/index.type";
import { upkeepRecordUrgencyEnum } from "@/utils/typings/equipManage/equipUpkeep/index.type";
import { recipientReasonEnum } from "@/utils/typings/equipManage/equipRepair/index.type";
import DileInputSelectItem from "@/components/dile-selectItem/selectItem-input/index.vue";
import DileSelectItemTable from "@/components/dile-selectItem/selectItem-table/index.vue";
import OutBoundForm from "@/views/moldManage/moldSpare/outBoundManage/outBound-form/index.vue";
import RelUpkeepItem from "@/views/moldManage/moldUpkeep/upkeepItem/upkeepItem-relTable/index.vue";
import RelSpareTable from "@/views/moldManage/moldSpare/spareLedger/spareLedger-relTable/index.vue";
import DileDrawer from "@/components/dile-drawer/index.vue";
import Dile_APi from "@/api";
const emit = defineEmits(["refresh"]);

let { t } = useI18n();
/**
 * @Author: xzh
 * @Descripttion: 出库表单实例
 * @Param:
 */
let outBoundFormRef = ref<any>(null);
/**
 * @Author: xzh
 * @Descripttion: 选择对象表格实例
 * @Param:
 */
let dileSelectItemTableRef = ref<any>(null);
/**
 * @Author: xzh
 * @Descripttion: 关联保养项目表格实例
 * @Param:
 */
let relUpkeepItemRef = ref<any>(null);
/**
 * @Author: xzh
 * @Descripttion: 备件明细表格实例
 * @Param:
 */
let relSpareTableRef = ref<any>(null);

/**
 * @Author: xzh
 * @Descripttion: 表单默认数据
 * @Param:
 */
let defaultData = () => ({
  id: 0,
  status: true, //状态
  // 保养任务信息
  code: "", //保养记录编号
  name: "", //保养记录名称
  urgencyLevel: "", //紧急程度
  isStop: false, //是否停机
  //更换备件
  isReplace: true, //是否更换备件
  mouldId: null,
  //模具信息
  relMold: {
    name: "", //模具名称
    code: "", //模具编码
    specification: "", //规格型号
    extJson: {
      typeName: "", //模具类型名称
      positionName: "", //存放位置
      factoryName: "", //所在工厂名称
    },
  },
  maintenancePlanId: null,
  //保养计划信息
  relUpkeepPlan: {
    code: "", //计划编号
    name: "", //计划名称
    //保养人员
    teamId: null, //保养班组
    manager: null, //保养负责人
    startDate: "", //计划开始时间
    endDate: "", //计划结束时间
    otherUser: "", //其他保养人
    extJson: {
      teamName: "", //保养班组名称
      managerName: "", //保养负责人名称
      otherPeopleName: "", //其他保养人名称
      executeRuleName: "", //执行规则名称
      executeRuleDescription: "", //执行规则描述
    },
  },
});
/**
 * @Author: xzh
 * @Descripttion: 保养计划表单参数
 * @Param:
 */
let upkeepRecordForm = reactive<object_Inf>({
  visible: false,
  loading: false,
  //表单数据
  formData: defaultData(),
  resoure: {
    //模具状态
    moldStateArr: [],
    //模具存放位置
    moldPositionArr: [],
  },
});

/**
 * @Author: xzh
 * @Descripttion: 表单实例
 * @Param:
 */
let formRef = ref<any>(null);

/**
 * @Author: xzh
 * @Descripttion:表单验证规则
 * @Param:
 * @param {*} computed
 */
let formRules = computed((): any => {
  return reactive({
    ["relMold.name"]: [
      {
        required: true,
        message:
          t("common.enter") + t("page.moldManageArr.moldArchivesArr.name"),
        trigger: "change",
      },
    ],
    name: [
      {
        required: true,
        message: t("common.enter") + t("page.moldUpkeepArr.upkeepPlanArr.name"),
        trigger: "change",
      },
    ],
    ["relUpkeepPlan.name"]: [
      {
        required: true,
        message: t("common.select") + t("page.moldUpkeepArr.upkeepPlan"),
        trigger: "change",
      },
    ],
    planType: [
      {
        required: true,
        message:
          t("common.select") + t("page.moldUpkeepArr.upkeepPlanArr.planType"),
        trigger: "change",
      },
    ],
    // executeRuleId: [
    //   {
    //     required: true,
    //     message:
    //       t("common.select") +
    //       t("page.moldUpkeepArr.upkeepPlanArr.executeRule"),
    //     trigger: "change",
    //   },
    // ],
  });
});

/**
 * @Author: xzh
 * @Descripttion:初始化加载
 * @Param:
 * @param {*} id 保养计划主键
 */
let init = async (id: number) => {
  let { visible, loading } = toRefs(upkeepRecordForm);
  visible.value = true;
  await nextTick();
  try {
    loading.value = true;
    //加载表单数据
    await initFormData(id);
  } finally {
    loading.value = false;
  }
};

/**
 * @Author: xzh
 * @Descripttion: 加载表单数据
 * @Param:
 */
let initFormData = async (id: number) => {
  let {
    model,
    mouldModel,
    planModel,
    sparePartDataList,
    sparePartRelations,
    projectDataList,
    projectRelations,
  }: object_Inf = !!id
    ? await Dile_APi.getMoldUpkeepRecordInfo(id)
    : { model: defaultData(), mouldModel: {}, planModel: {} };

  Object.assign(upkeepRecordForm.formData, {
    ...model,
    //关联模具信息
    mouldId: mouldModel.id,
    relMold: {
      ...model.relMold,
      ...mouldModel,
    },
    //关联保养计划信息
    maintenancePlanId: planModel.id,
    relUpkeepPlan: {
      ...model.relUpkeepPlan,
      ...planModel,
    },
  });
  //格式化关联保养项目信息
  if (projectDataList?.length > 0) {
    let relUpkeepItemArr = projectDataList
      .map((upkeepItem: object_Inf) => {
        let { id } = projectRelations?.find(
          (x: object_Inf) => x.maintenanceProjectId == upkeepItem.id
        );
        return !!id
          ? {
              ...upkeepItem,
              relId: id,
            }
          : {};
      })
      .filter((x: object_Inf) => !!x.id);
    //加载关联保养项目表格
    relUpkeepItemRef.value.initTableData(relUpkeepItemArr);
  }
  //格式化关联备件信息
  // if (sparePartDataList?.length > 0) {
  //   let relSpareArr = sparePartDataList
  //     .map((spare: object_Inf) => {
  //       let { id, deliveryNumber } = sparePartRelations?.find(
  //         (x: object_Inf) => x.sparePartId == spare.id
  //       );
  //       return !!id
  //         ? {
  //             ...spare,
  //             deliveryNumber,
  //             relId: id,
  //           }
  //         : {};
  //     })
  //     .filter((x: object_Inf) => !!x.id);
  //   //加载关联备件表格
  //   relSpareTableRef.value.initTableData(relSpareArr);
  // }
};

/**
 * @Author: xzh
 * @Descripttion: 关联模具选中
 * @Param:
 * @param {*} mold
 */
let handleMoldSelected = (moldArr: Array<object_Inf>) => {
  let { formData } = toRefs(upkeepRecordForm),
    mold: object_Inf = moldArr.find(() => true) || {};
  Object.assign(formData.value, {
    ...formData.value,
    mouldId: mold.id,
    relMold: mold,
  });
};
/**
 * @Author: xzh
 * @Descripttion: 保养计划选择事件
 * @Param:
 */
let handleUpkeepPlanSelected = async (upkeepPlanArr: Array<object_Inf>) => {
  let { formData } = toRefs(upkeepRecordForm),
    { relUpkeepPlan } = formData.value,
    upkeepPlan: object_Inf = upkeepPlanArr.find(() => true) || {},
    { getTableData = () => {}, initTableData = () => {} } =
      relUpkeepItemRef.value;

  //根据保养计划获取保养项目
  let data = await Dile_APi.getMoldUpkeepItemByPlan(upkeepPlan.id);

  let relUpkeepItemArr = [
    //排除现有计划对应保养项目
    ...(getTableData() || []).filter((x: object_Inf) =>
      !!x.upkeepPlanId ? x.upkeepPlanId != relUpkeepPlan.id : true
    ),
    //添加选择计划对应保养项目
    ...data.map((x) => ({ ...x, upkeepPlanId: upkeepPlan.id })),
  ];
  //修改表格数据源
  initTableData(relUpkeepItemArr);

  Object.assign(formData.value.relUpkeepPlan, upkeepPlan);
};
/**
 * @Author: xzh
 * @Descripttion: 执行规则选择事件
 * @Param:
 * @param {*} executeRuleArr
 */
let handleExecuteRuleSelected = (executeRuleArr: Array<object_Inf>) => {
  let { formData } = toRefs(upkeepRecordForm),
    executeRule = executeRuleArr.find(() => true);
  Object.assign(formData.value.relExecuteRule, executeRule);
};
/**
 * @Author: xzh
 * @Descripttion: 保存事件
 * @Param:
 */
let hanldeSure = async () => {
  let { formData, loading, visible } = toRefs(upkeepRecordForm),
    valid = await formRef.value.validate(),
    outBoundData = await outBoundFormRef.value.hanldeSaveForm(false);
  //表单验证&&关联备件验证&&防止重复提交
  if (!valid || !verifyRelSpare() || !!loading.value || outBoundData == false) {
    return false;
  }
  try {
    loading.value = true;
    debugger;
    await Dile_APi.saveMoldUpkeepRecord({
      //保养记录信息
      maintenanceRecordParameter: {
        model: formData.value,
        //格式化关联对象信息
        ...fomatRelItem(),
      },
      //出库信息
      stockOutParameter: outBoundData,
    });
    //触发刷新回调
    emit("refresh");
    //提示成功
    ElNotification({
      message: t("common.message.OperationSuccess"),
      type: "success",
    });
    //关闭弹框
    visible.value = false;
  } finally {
    loading.value = false;
  }
};

/**
 * @Author: xzh
 * @Descripttion: 验证关联备件
 * @Param:
 */
let verifyRelSpare = () => {
  let relSpareData: object_Inf = relSpareTableRef.value.getTableData();
  //获取领用为空数组
  let emptyUseNumArr = relSpareData.filter(
    (x: object_Inf) => !!x.id && !x.deliveryNumber
  );
  if (emptyUseNumArr.length > 0) {
    ElNotification({
      message: `[${emptyUseNumArr
        .map((x: object_Inf) => x.name)
        .join(",")}]:${t("common.enter")}${t(
        "page.moldSpareArr.spareLedgerArr.useNum"
      )}`,
      type: "warning",
    });
    return false;
  }
  return true;
};

/**
 * @Author: xzh
 * @Descripttion: 格式化关联对象信息
 * @Param:
 */
let fomatRelItem = () => {
  let { id } = upkeepRecordForm.formData,
    relUpkeepItemData: object_Inf = relUpkeepItemRef.value.getRelData(),
    relSpareData: object_Inf = relSpareTableRef.value.getRelData();
  //格式化关联保养项目信息
  Object.keys(relUpkeepItemData)
    .filter((x) => x != "deleteRelations")
    .forEach(
      (relkey) =>
        (relUpkeepItemData[relkey] = relUpkeepItemData[relkey].map(
          (x: object_Inf) => {
            let { id: upkeepItemId, relId } = x;
            return {
              id: relId,
              maintenanceProjectId: upkeepItemId,
              maintenanceRecordId: id,
            };
          }
        ))
    );
  //格式化关联备件信息
  Object.keys(relSpareData)
    .filter((x) => x != "deleteRelations")
    .forEach(
      (relkey) =>
        (relSpareData[relkey] = relSpareData[relkey].map((x: object_Inf) => {
          let { id: sparePartId, deliveryNumber, relId } = x;
          return {
            id: relId,
            sparePartId,
            maintenanceRecordId: id,
            deliveryNumber,
          };
        }))
    );
  return {
    //保养项目关联信息
    addProjectRelations: relUpkeepItemData.addRelations,
    eidtProjectRelations: relUpkeepItemData.eidtRelations,
    deleteProjectRelations: relUpkeepItemData.deleteRelations,
    //备件关联信息
    addSparePartRelations: relSpareData.addRelations,
    eidtSparePartRelations: relSpareData.eidtRelations,
    deleteSparePartRelations: relSpareData.deleteRelations,
  };
};

defineExpose({
  init,
});
</script>
<style lang="scss" scoped>
:deep(.el-form) {
  width: 100%;
}
</style>
